package me.leiusual.sharing.util.extension

import androidx.lifecycle.LiveData
import androidx.lifecycle.Observer
import me.leiusual.sharing.repository.model.Data
import timber.log.Timber

/**
 * 获取值
 */
val <T> LiveData<T>.requireValue: T
  get() = value ?: throw IllegalArgumentException("value is null")

/**
 * 观察一次
 */
fun <T> LiveData<Data<T>>.observeOnce(
    error: ((error: Throwable) -> Unit)? = null,
    success: ((data: T) -> Unit)? = null
) {
  observeForever(object : Observer<Data<T>> {
    override fun onChanged(it: Data<T>?) {
      Timber.v("observeOnce = %s", it)
      when (it) {
        is Data.Loading -> {
          // ignore
        }
        is Data.Error -> {
          removeObserver(this)
          error?.invoke(it.error)
        }
        is Data.Success -> {
          removeObserver(this)
          success?.invoke(it.data)
        }
      }
    }
  })
}